"""
Visualization module.
Generates text-based descriptions and analysis summaries instead of plots.
"""

import warnings
import numpy as np
from typing import Dict, List, Any, Optional, Tuple
import os

class Visualizer:
    """Creates text-based descriptions and analysis summaries instead of visual plots."""
    
    def __init__(self, config, output_dir: str = "output"):
        self.config = config
        self.output_dir = output_dir
        self.descriptions_created = []
        
        # Create output directory if it doesn't exist
        os.makedirs(output_dir, exist_ok=True)
        
    def create_comprehensive_report(self, results: Dict[str, Any], filename_prefix: str = "analysis") -> List[str]:
        """Create comprehensive text-based analysis descriptions."""
        
        if not self.config.generate_plots:
            return []
            
        from .text_visualizer import TextVisualizer
        text_viz = TextVisualizer(self.config, self.output_dir)
        created_files = text_viz.create_text_descriptions(results, filename_prefix)
        
        self.descriptions_created = created_files
        return created_files
        
    def _create_text_visualizations(self, text_results: Dict[str, Any], prefix: str) -> List[str]:
        """Create visualizations for text analysis results."""
        created_files = []
        
        # Word frequency chart
        if 'word_frequency' in text_results and text_results['word_frequency']:
            filename = self._create_word_frequency_chart(text_results['word_frequency'], prefix)
            if filename:
                created_files.append(filename)
                
        # Sentence length distribution
        if 'sentence_analysis' in text_results:
            filename = self._create_sentence_distribution_chart(text_results['sentence_analysis'], prefix)
            if filename:
                created_files.append(filename)
                
        # Part of speech distribution
        if 'pos_distribution' in text_results and text_results['pos_distribution']:
            filename = self._create_pos_distribution_chart(text_results['pos_distribution'], prefix)
            if filename:
                created_files.append(filename)
                
        return created_files
        
    def _create_numerical_visualizations(self, num_results: Dict[str, Any], prefix: str) -> List[str]:
        """Create visualizations for numerical analysis results."""
        created_files = []
        
        # Number distribution histogram
        if 'distribution' in num_results and num_results['distribution']:
            filename = self._create_number_distribution_chart(num_results['distribution'], prefix)
            if filename:
                created_files.append(filename)
                
        # Anomaly summary chart
        if 'anomalies' in num_results:
            filename = self._create_anomaly_summary_chart(num_results['anomalies'], prefix)
            if filename:
                created_files.append(filename)
                
        return created_files
        
    def _create_trend_visualizations(self, trend_results: Dict[str, Any], prefix: str) -> List[str]:
        """Create visualizations for trend analysis results."""
        created_files = []
        
        # Individual sequence plots
        for seq_name, seq_analysis in trend_results.items():
            if seq_name == 'comparative_analysis':
                continue
                
            if isinstance(seq_analysis, dict) and 'data_points' in seq_analysis:
                filename = self._create_sequence_trend_chart(seq_analysis, seq_name, prefix)
                if filename:
                    created_files.append(filename)
                    
        # Comparative analysis chart
        if 'comparative_analysis' in trend_results:
            filename = self._create_comparative_analysis_chart(trend_results['comparative_analysis'], prefix)
            if filename:
                created_files.append(filename)
                
        return created_files
        
    def _create_word_frequency_chart(self, word_freq: Dict[str, int], prefix: str) -> Optional[str]:
        """Create word frequency bar chart."""
        try:
            fig, ax = plt.subplots(figsize=self.config.figure_size, dpi=self.config.plot_dpi)
            
            # Get top 20 words
            top_words = list(word_freq.items())[:20]
            words, counts = zip(*top_words) if top_words else ([], [])
            
            if words:
                bars = ax.bar(range(len(words)), counts, color='skyblue', alpha=0.7)
                ax.set_xlabel('Words')
                ax.set_ylabel('Frequency')
                ax.set_title('Top 20 Most Frequent Words')
                ax.set_xticks(range(len(words)))
                ax.set_xticklabels(words, rotation=45, ha='right')
                
                # Add value labels on bars
                for bar, count in zip(bars, counts):
                    height = bar.get_height()
                    ax.text(bar.get_x() + bar.get_width()/2., height + 0.01*max(counts),
                           f'{count}', ha='center', va='bottom')
                           
                plt.tight_layout()
                
                filename = os.path.join(self.output_dir, f"{prefix}_word_frequency.png")
                plt.savefig(filename, bbox_inches='tight')
                plt.close()
                return filename
                
        except Exception as e:
            print(f"Error creating word frequency chart: {e}")
            
        return None
        
    def _create_sentence_distribution_chart(self, sentence_stats: Dict[str, Any], prefix: str) -> Optional[str]:
        """Create sentence length distribution chart."""
        try:
            fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6), dpi=self.config.plot_dpi)
            
            # Pie chart for sentence categories
            categories = ['Short (≤10)', 'Medium (11-20)', 'Long (>20)']
            sizes = [
                sentence_stats.get('short_sentences_pct', 0),
                sentence_stats.get('medium_sentences_pct', 0), 
                sentence_stats.get('long_sentences_pct', 0)
            ]
            
            if sum(sizes) > 0:
                ax1.pie(sizes, labels=categories, autopct='%1.1f%%', startangle=90)
                ax1.set_title('Sentence Length Distribution')
                
            # Bar chart for statistics
            stats_names = ['Mean', 'Median', 'Min', 'Max']
            stats_values = [
                sentence_stats.get('mean', 0),
                sentence_stats.get('median', 0),
                sentence_stats.get('min', 0),
                sentence_stats.get('max', 0)
            ]
            
            bars = ax2.bar(stats_names, stats_values, color=['blue', 'green', 'orange', 'red'], alpha=0.7)
            ax2.set_ylabel('Words per Sentence')
            ax2.set_title('Sentence Length Statistics')
            
            # Add value labels
            for bar, value in zip(bars, stats_values):
                height = bar.get_height()
                ax2.text(bar.get_x() + bar.get_width()/2., height + 0.01*max(stats_values),
                        f'{value:.1f}', ha='center', va='bottom')
                        
            plt.tight_layout()
            
            filename = os.path.join(self.output_dir, f"{prefix}_sentence_distribution.png")
            plt.savefig(filename, bbox_inches='tight')
            plt.close()
            return filename
            
        except Exception as e:
            print(f"Error creating sentence distribution chart: {e}")
            
        return None
        
    def _create_pos_distribution_chart(self, pos_dist: Dict[str, int], prefix: str) -> Optional[str]:
        """Create part-of-speech distribution chart."""
        try:
            fig, ax = plt.subplots(figsize=(10, 6), dpi=self.config.plot_dpi)
            
            pos_types = list(pos_dist.keys())
            counts = list(pos_dist.values())
            
            colors = plt.cm.Set3(np.linspace(0, 1, len(pos_types)))
            bars = ax.bar(pos_types, counts, color=colors, alpha=0.7)
            
            ax.set_xlabel('Part of Speech Category')
            ax.set_ylabel('Count')
            ax.set_title('Part-of-Speech Distribution')
            ax.tick_params(axis='x', rotation=45)
            
            # Add value labels
            for bar, count in zip(bars, counts):
                height = bar.get_height()
                ax.text(bar.get_x() + bar.get_width()/2., height + 0.01*max(counts),
                       f'{count}', ha='center', va='bottom')
                       
            plt.tight_layout()
            
            filename = os.path.join(self.output_dir, f"{prefix}_pos_distribution.png")
            plt.savefig(filename, bbox_inches='tight')
            plt.close()
            return filename
            
        except Exception as e:
            print(f"Error creating POS distribution chart: {e}")
            
        return None
        
    def _create_number_distribution_chart(self, distribution: Dict[str, Any], prefix: str) -> Optional[str]:
        """Create number distribution visualization."""
        try:
            fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12), dpi=self.config.plot_dpi)
            
            # Basic statistics bar chart
            stats_names = ['Count', 'Mean', 'Median', 'Std', 'Min', 'Max']
            stats_values = [
                distribution.get('count', 0),
                distribution.get('mean', 0),
                distribution.get('median', 0),
                distribution.get('std', 0),
                distribution.get('min', 0),
                distribution.get('max', 0)
            ]
            
            bars1 = ax1.bar(stats_names, stats_values, color='lightblue', alpha=0.7)
            ax1.set_title('Number Distribution Statistics')
            ax1.set_ylabel('Value')
            ax1.tick_params(axis='x', rotation=45)
            
            # Number type distribution
            type_counts = {
                'Positive': distribution.get('positives_count', 0),
                'Negative': distribution.get('negatives_count', 0),
                'Zeros': distribution.get('zeros_count', 0)
            }
            
            if sum(type_counts.values()) > 0:
                ax2.pie(type_counts.values(), labels=type_counts.keys(), autopct='%1.1f%%', startangle=90)
                ax2.set_title('Number Type Distribution')
                
            # Quartile analysis
            quartile_names = ['Q25', 'Median', 'Q75']
            quartile_values = [
                distribution.get('q25', 0),
                distribution.get('median', 0),
                distribution.get('q75', 0)
            ]
            
            bars3 = ax3.bar(quartile_names, quartile_values, color='lightgreen', alpha=0.7)
            ax3.set_title('Quartile Analysis')
            ax3.set_ylabel('Value')
            
            # Magnitude analysis (if available)
            if 'magnitude_analysis' in distribution:
                mag_analysis = distribution['magnitude_analysis']
                mag_names = ['Mean Log Mag', 'Std Log Mag', 'Mag Range']
                mag_values = [
                    mag_analysis.get('mean_log_magnitude', 0),
                    mag_analysis.get('std_log_magnitude', 0),
                    mag_analysis.get('magnitude_range', 0)
                ]
                
                bars4 = ax4.bar(mag_names, mag_values, color='lightcoral', alpha=0.7)
                ax4.set_title('Magnitude Analysis (Log Scale)')
                ax4.set_ylabel('Log Value')
            else:
                ax4.text(0.5, 0.5, 'No magnitude\nanalysis available', 
                        ha='center', va='center', transform=ax4.transAxes, fontsize=12)
                ax4.set_title('Magnitude Analysis')
                
            plt.tight_layout()
            
            filename = os.path.join(self.output_dir, f"{prefix}_number_distribution.png")
            plt.savefig(filename, bbox_inches='tight')
            plt.close()
            return filename
            
        except Exception as e:
            print(f"Error creating number distribution chart: {e}")
            
        return None
        
    def _create_anomaly_summary_chart(self, anomalies: Dict[str, Any], prefix: str) -> Optional[str]:
        """Create anomaly summary visualization."""
        try:
            fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6), dpi=self.config.plot_dpi)
            
            # Anomaly types distribution
            if 'summary' in anomalies and 'anomaly_types' in anomalies['summary']:
                anomaly_types = anomalies['summary']['anomaly_types']
                types = list(anomaly_types.keys())
                counts = list(anomaly_types.values())
                
                if sum(counts) > 0:
                    colors = plt.cm.Set1(np.linspace(0, 1, len(types)))
                    bars = ax1.bar(types, counts, color=colors, alpha=0.7)
                    ax1.set_title('Anomaly Types Distribution')
                    ax1.set_ylabel('Count')
                    ax1.tick_params(axis='x', rotation=45)
                    
                    # Add value labels
                    for bar, count in zip(bars, counts):
                        if count > 0:
                            height = bar.get_height()
                            ax1.text(bar.get_x() + bar.get_width()/2., height + 0.01*max(counts),
                                   f'{count}', ha='center', va='bottom')
                else:
                    ax1.text(0.5, 0.5, 'No anomalies detected', 
                            ha='center', va='center', transform=ax1.transAxes, fontsize=12)
                    ax1.set_title('Anomaly Types Distribution')
                    
            # Summary metrics
            if 'summary' in anomalies:
                summary = anomalies['summary']
                metrics = {
                    'Total Anomalies': summary.get('total_anomalies', 0),
                    'Anomaly Rate (%)': summary.get('anomaly_rate', 0) * 100
                }
                
                metric_names = list(metrics.keys())
                metric_values = list(metrics.values())
                
                bars2 = ax2.bar(metric_names, metric_values, color=['red', 'orange'], alpha=0.7)
                ax2.set_title('Anomaly Summary Metrics')
                ax2.set_ylabel('Value')
                
                # Add value labels
                for bar, value in zip(bars2, metric_values):
                    height = bar.get_height()
                    ax2.text(bar.get_x() + bar.get_width()/2., height + 0.01*max(metric_values),
                           f'{value:.1f}', ha='center', va='bottom')
                           
            plt.tight_layout()
            
            filename = os.path.join(self.output_dir, f"{prefix}_anomaly_summary.png")
            plt.savefig(filename, bbox_inches='tight')
            plt.close()
            return filename
            
        except Exception as e:
            print(f"Error creating anomaly summary chart: {e}")
            
        return None
        
    def _create_sequence_trend_chart(self, seq_analysis: Dict[str, Any], seq_name: str, prefix: str) -> Optional[str]:
        """Create trend visualization for a single sequence."""
        try:
            # This would need access to the original sequence data
            # For now, create a summary chart based on available analysis
            
            fig, ax = plt.subplots(figsize=(12, 6), dpi=self.config.plot_dpi)
            
            # Create a summary visualization
            metrics = seq_analysis.get('trend_metrics', {})
            data_range = seq_analysis.get('data_range', {})
            
            info_text = f"""Sequence: {seq_name}
Data Points: {seq_analysis.get('data_points', 'N/A')}
Trend Type: {seq_analysis.get('trend_type', 'N/A')}

Metrics:
Mean Change: {metrics.get('mean_change', 'N/A'):.6f}
Stability Score: {metrics.get('stability_score', 'N/A'):.4f}
Confidence: {metrics.get('confidence_score', 'N/A'):.4f}

Data Range:
First: {data_range.get('first', 'N/A')}
Last: {data_range.get('last', 'N/A')}
Change: {data_range.get('change', 'N/A')}"""
            
            ax.text(0.1, 0.5, info_text, transform=ax.transAxes, fontsize=11,
                   verticalalignment='center', fontfamily='monospace',
                   bbox=dict(boxstyle='round', facecolor='lightgray', alpha=0.8))
                   
            ax.set_xlim(0, 1)
            ax.set_ylim(0, 1)
            ax.set_title(f'Trend Analysis Summary: {seq_name}')
            ax.axis('off')
            
            filename = os.path.join(self.output_dir, f"{prefix}_trend_{seq_name.replace(' ', '_')}.png")
            plt.savefig(filename, bbox_inches='tight')
            plt.close()
            return filename
            
        except Exception as e:
            print(f"Error creating sequence trend chart: {e}")
            
        return None
        
    def _create_comparative_analysis_chart(self, comp_analysis: Dict[str, Any], prefix: str) -> Optional[str]:
        """Create comparative analysis visualization."""
        try:
            fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12), dpi=self.config.plot_dpi)
            
            # Sequence count and length statistics
            length_stats = comp_analysis.get('length_statistics', {})
            if length_stats:
                stats_names = ['Min Length', 'Max Length', 'Mean Length']
                stats_values = [
                    length_stats.get('min_length', 0),
                    length_stats.get('max_length', 0),
                    length_stats.get('mean_length', 0)
                ]
                
                bars1 = ax1.bar(stats_names, stats_values, color='skyblue', alpha=0.7)
                ax1.set_title('Sequence Length Statistics')
                ax1.set_ylabel('Length')
                
            # Trend distribution
            trend_dist = comp_analysis.get('trend_distribution', {})
            if trend_dist:
                trend_types = list(trend_dist.keys())
                trend_counts = list(trend_dist.values())
                
                colors = plt.cm.Set3(np.linspace(0, 1, len(trend_types)))
                ax2.pie(trend_counts, labels=trend_types, autopct='%1.1f%%', startangle=90, colors=colors)
                ax2.set_title('Trend Type Distribution')
                
            # Convergence comparison
            conv_comp = comp_analysis.get('convergence_comparison', {})
            if conv_comp:
                conv_names = ['Best Convergence', 'Worst Convergence', 'Mean Convergence']
                conv_values = [
                    conv_comp.get('best_convergence', 0),
                    conv_comp.get('worst_convergence', 0),
                    conv_comp.get('mean_convergence_ratio', 0)
                ]
                
                bars3 = ax3.bar(conv_names, conv_values, color='lightgreen', alpha=0.7)
                ax3.set_title('Convergence Rate Comparison')
                ax3.set_ylabel('Convergence Ratio')
                ax3.tick_params(axis='x', rotation=45)
                
            # Summary info
            summary_text = f"""Comparative Analysis Summary

Sequence Count: {comp_analysis.get('sequence_count', 'N/A')}

Length Statistics:
Min: {length_stats.get('min_length', 'N/A')}
Max: {length_stats.get('max_length', 'N/A')}
Mean: {length_stats.get('mean_length', 'N/A'):.1f}
Std: {length_stats.get('std_length', 'N/A'):.1f}

Convergence:
Best: {conv_comp.get('best_convergence', 'N/A')}
Worst: {conv_comp.get('worst_convergence', 'N/A')}"""
            
            ax4.text(0.1, 0.5, summary_text, transform=ax4.transAxes, fontsize=10,
                    verticalalignment='center', fontfamily='monospace',
                    bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.8))
            ax4.set_title('Summary Information')
            ax4.axis('off')
            
            plt.tight_layout()
            
            filename = os.path.join(self.output_dir, f"{prefix}_comparative_analysis.png")
            plt.savefig(filename, bbox_inches='tight')
            plt.close()
            return filename
            
        except Exception as e:
            print(f"Error creating comparative analysis chart: {e}")
            
        return None
        
    def _create_summary_dashboard(self, results: Dict[str, Any], prefix: str) -> Optional[str]:
        """Create a comprehensive summary dashboard."""
        try:
            fig = plt.figure(figsize=(20, 16), dpi=self.config.plot_dpi)
            
            # Create a grid layout
            gs = fig.add_gridspec(4, 4, hspace=0.3, wspace=0.3)
            
            # Title
            fig.suptitle('Structural Information Extraction - Analysis Dashboard', fontsize=20, fontweight='bold')
            
            # Text analysis summary (top-left)
            ax1 = fig.add_subplot(gs[0, :2])
            self._add_text_summary(ax1, results.get('text_analysis', {}))
            
            # Numerical analysis summary (top-right)
            ax2 = fig.add_subplot(gs[0, 2:])
            self._add_numerical_summary(ax2, results.get('numerical_analysis', {}))
            
            # File information (middle-left)
            ax3 = fig.add_subplot(gs[1, :2])
            self._add_file_summary(ax3, results.get('file_info', {}))
            
            # Health scores (middle-right)
            ax4 = fig.add_subplot(gs[1, 2:])
            self._add_health_scores(ax4, results)
            
            # Trend analysis summary (bottom)
            ax5 = fig.add_subplot(gs[2:, :])
            self._add_trend_summary(ax5, results.get('trend_analysis', {}))
            
            filename = os.path.join(self.output_dir, f"{prefix}_dashboard.png")
            plt.savefig(filename, bbox_inches='tight')
            plt.close()
            return filename
            
        except Exception as e:
            print(f"Error creating summary dashboard: {e}")
            
        return None
        
    def _add_text_summary(self, ax, text_results: Dict[str, Any]):
        """Add text analysis summary to subplot."""
        basic_stats = text_results.get('basic_statistics', {})
        complexity = text_results.get('complexity_metrics', {})
        
        summary_text = f"""TEXT ANALYSIS SUMMARY

Basic Statistics:
• Characters: {basic_stats.get('total_characters', 'N/A'):,}
• Words: {basic_stats.get('total_words', 'N/A'):,}
• Sentences: {basic_stats.get('total_sentences', 'N/A'):,}
• Lines: {basic_stats.get('total_lines', 'N/A'):,}
• Avg Sentence Length: {basic_stats.get('avg_sentence_length', 'N/A'):.1f} words
• Vocabulary Size: {basic_stats.get('vocabulary_size', 'N/A'):,}
• Lexical Diversity: {basic_stats.get('lexical_diversity', 'N/A'):.3f}

Complexity:
• Complexity Score: {complexity.get('complexity_score', 'N/A'):.3f}"""
        
        ax.text(0.05, 0.95, summary_text, transform=ax.transAxes, fontsize=10,
               verticalalignment='top', fontfamily='monospace',
               bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.8))
        ax.set_title('Text Structure Analysis')
        ax.axis('off')
        
    def _add_numerical_summary(self, ax, num_results: Dict[str, Any]):
        """Add numerical analysis summary to subplot."""
        summary = num_results.get('summary', {})
        health_score = num_results.get('health_score', 0)
        anomalies = num_results.get('anomalies', {}).get('summary', {})
        
        summary_text = f"""NUMERICAL ANALYSIS SUMMARY

Numbers Found:
• Total Numbers: {summary.get('total_numbers_found', 'N/A'):,}
• Valid Numbers: {summary.get('valid_numbers', 'N/A'):,}
• Invalid Numbers: {summary.get('invalid_numbers', 'N/A'):,}
• Scientific Notation: {summary.get('scientific_notation_count', 'N/A'):,}

Anomalies:
• Total Anomalies: {anomalies.get('total_anomalies', 'N/A'):,}
• Anomaly Rate: {anomalies.get('anomaly_rate', 0)*100:.1f}%

Health Score: {health_score:.3f}"""
        
        ax.text(0.05, 0.95, summary_text, transform=ax.transAxes, fontsize=10,
               verticalalignment='top', fontfamily='monospace',
               bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.8))
        ax.set_title('Numerical Analysis')
        ax.axis('off')
        
    def _add_file_summary(self, ax, file_info: Dict[str, Any]):
        """Add file information summary to subplot."""
        summary_text = f"""FILE INFORMATION

File Details:
• Filename: {file_info.get('filename', 'N/A')}
• Size: {file_info.get('size_bytes', 'N/A'):,} bytes
• Encoding: {file_info.get('encoding', 'N/A')}
• Analysis Date: {file_info.get('analysis_date', 'N/A')}
• Processing Time: {file_info.get('processing_time', 'N/A'):.2f}s"""
        
        ax.text(0.05, 0.95, summary_text, transform=ax.transAxes, fontsize=10,
               verticalalignment='top', fontfamily='monospace',
               bbox=dict(boxstyle='round', facecolor='lightyellow', alpha=0.8))
        ax.set_title('File Information')
        ax.axis('off')
        
    def _add_health_scores(self, ax, results: Dict[str, Any]):
        """Add health scores visualization to subplot."""
        # Extract health-related scores
        numerical_health = results.get('numerical_analysis', {}).get('health_score', 0)
        text_complexity = results.get('text_analysis', {}).get('complexity_metrics', {}).get('complexity_score', 0)
        
        # Create a simple bar chart of scores
        scores = {
            'Numerical\nHealth': numerical_health,
            'Text\nComplexity': text_complexity
        }
        
        score_names = list(scores.keys())
        score_values = list(scores.values())
        
        colors = ['green' if v > 0.7 else 'orange' if v > 0.4 else 'red' for v in score_values]
        bars = ax.bar(score_names, score_values, color=colors, alpha=0.7)
        
        ax.set_title('Quality Scores')
        ax.set_ylabel('Score (0-1)')
        ax.set_ylim(0, 1)
        
        # Add value labels
        for bar, value in zip(bars, score_values):
            height = bar.get_height()
            ax.text(bar.get_x() + bar.get_width()/2., height + 0.02,
                   f'{value:.3f}', ha='center', va='bottom')
                   
    def _add_trend_summary(self, ax, trend_results: Dict[str, Any]):
        """Add trend analysis summary to subplot."""
        if not trend_results:
            ax.text(0.5, 0.5, 'No trend analysis available', 
                   ha='center', va='center', transform=ax.transAxes, fontsize=14)
            ax.set_title('Trend Analysis Summary')
            ax.axis('off')
            return
            
        # Create a summary table of trend information
        trend_info = []
        for seq_name, seq_analysis in trend_results.items():
            if seq_name == 'comparative_analysis' or not isinstance(seq_analysis, dict):
                continue
                
            trend_info.append([
                seq_name[:20],  # Truncate long names
                str(seq_analysis.get('data_points', 'N/A')),
                seq_analysis.get('trend_type', 'N/A')[:15],
                f"{seq_analysis.get('trend_metrics', {}).get('confidence_score', 0):.3f}"
            ])
            
        if trend_info:
            # Create table
            table_data = [['Sequence', 'Points', 'Trend Type', 'Confidence']] + trend_info
            table = ax.table(cellText=table_data[1:], colLabels=table_data[0],
                           cellLoc='center', loc='center')
            table.auto_set_font_size(False)
            table.set_fontsize(9)
            table.scale(1, 1.5)
            
            # Style the header row
            for i in range(len(table_data[0])):
                table[(0, i)].set_facecolor('#4CAF50')
                table[(0, i)].set_text_props(weight='bold', color='white')
                
        ax.set_title('Trend Analysis Summary')
        ax.axis('off')
